from django.shortcuts import render, redirect, HttpResponse

from rbac.forms.userinfo import UserInfoAddModelForm, UserInfoEditModelForm, UserInfoResetPasswordModelForm
from rbac.models import UserInfo
from rbac.service.urls import memory_reverse


def userinfo_list(request):
    """
    用户列表
    :param request:
    :return:
    """
    userinfo_queryset = UserInfo.objects.all()
    return render(request, "rbac/userinfo_list.html", {'data_list': userinfo_queryset})


def userinfo_add(request):
    """
    添加用户
    :param request:
    :return:
    """
    origin_url = memory_reverse(request, 'rbac:userinfo_list')
    if request.method == 'GET':
        form = UserInfoAddModelForm()
        return render(request, 'rbac/change.html', {'form': form})
    form = UserInfoAddModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(origin_url)
    return render(request, 'rbac/change.html', {'form': form})


def userinfo_edit(request, pk):
    """
    编辑用户
    :param request:
    :param pk:
    :return:
    """
    obj = UserInfo.objects.filter(id=pk).first()
    origin_url = memory_reverse(request, "rbac:userinfo_list")
    if not obj:
        return HttpResponse("数据不存在")
    if request.method == 'GET':
        form = UserInfoEditModelForm(instance=obj)
        return render(request, 'rbac/change.html', {'form': form})
    form = UserInfoEditModelForm(instance=obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(origin_url)
    return render(request, 'rbac/change.html', {'form': form})


def userinfo_del(request, pk):
    """
    删除用户
    :param request:
    :param pk:
    :return:
    """
    obj = UserInfo.objects.filter(id=pk).first()
    origin_url = memory_reverse(request, 'rbac:userinfo_list')
    if not obj:
        return HttpResponse("数据不存在")

    if request.method == "GET":
        return render(request, 'rbac/delete.html', {'cancel_url': origin_url})

    obj.delete()
    return redirect(origin_url)


def userinfo_reset_password(request, pk):
    """
    密码重置
    :param request:
    :param pk:
    :return:
    """
    obj = UserInfo.objects.filter(id=pk).first()
    origin_url = memory_reverse(request, "rbac:userinfo_list")
    if not obj:
        return HttpResponse("数据不存在")
    if request.method == 'GET':
        form = UserInfoResetPasswordModelForm(instance=obj)
        return render(request, 'rbac/change.html', {'form': form})
    form = UserInfoResetPasswordModelForm(instance=obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(origin_url)
    return render(request, 'rbac/change.html', {'form': form})
